<?php
/* 
Plugin Name: WoW Armory 
Plugin URI: http://timsworld.nfshost.com/wordpress-plugins/wow-armory-wp-plugin/ 
Description: Shows your character's Armory info  
Version: 2.4
Author: Tim (SeiferTim) Hely
Author URI: http://timsworld.nfshost.com
*/  


	class WoWArmory {
    var $plugin_folder = '';

    var $default_options = array(
            'cname' => '', 
            'realm' => '',
            'realmtype' => '',
            'show_g' => true,
            'show_p' => true,
            'show_a' => true,
            'lang' => 'En',
            'linkback' => false,
            'talents' => true,
    );

    

  
  
  function WoWArmory() {
        $this->plugin_folder = get_option('home').'/'.PLUGINDIR.'/wow-armory/';
        wp_enqueue_script('wowhead',"http://www.wowhead.com/widgets/power.js");
        wp_enqueue_script('wow_armory', get_bloginfo('wpurl') . '/wp-content/plugins/wow-armory/js/armory.js',array('jquery'));    
        wp_enqueue_style('wow_armory_css', get_bloginfo('wpurl') . '/wp-content/plugins/wow-armory/css/style.css');      
    }

    function init() {
        if (!$options = get_option('widget_wow_armory'))
            $options = array();
            
        $widget_ops = array('classname' => 'widget_wow_armory', 'description' => 'WoW Armory');
        $control_ops = array('width' => 250, 'height' => 100, 'id_base' => 'wowarmory');
        $name = 'WoW Armory';
        
        $registered = false;
        foreach (array_keys($options) as $o) {
            if (!isset($options[$o]['cname']))
                continue;
                
            $id = "wowarmory-$o";
            $registered = true;
            wp_register_sidebar_widget($id, $name, array(&$this, 'widget'), $widget_ops, array( 'number' => $o ) );
            wp_register_widget_control($id, $name, array(&$this, 'control'), $control_ops, array( 'number' => $o ) );
        }
        if (!$registered) {
            wp_register_sidebar_widget('wowarmory-1', $name, array(&$this, 'widget'), $widget_ops, array( 'number' => -1 ) );
            wp_register_widget_control('wowarmory-1', $name, array(&$this, 'control'), $control_ops, array( 'number' => -1 ) );
        }
    }

    function widget($args, $widget_args = 1) {
        
        extract($args);
        global $post;

        if (is_numeric($widget_args))
            $widget_args = array('number' => $widget_args);
        $widget_args = wp_parse_args($widget_args, array( 'number' => -1 ));
        extract($widget_args, EXTR_SKIP);
        $options_all = get_option('widget_wow_armory');
        if (!isset($options_all[$number]))
            return;

        $options = $options_all[$number];

        echo $before_widget;
        echo $before_title . ' Armory for ' . $options["cname"] . $after_title;	   
        echo '<div id="armory-'.$number.'" class="armory_display">';
        echo $this->getArmory(
						$options['cname'],
						$options['realm'],
						$options['realmtype'],
						($options['show_g']) ? '1': '0',
						($options['show_p']) ? ' 1': '0',
						($options['show_a']) ? ' 1': '0',
						$options['lang'],
						($options['linkback']) ? ' 1': '0',
						($options['talents']) ? ' 1': '0'
					);
        echo "</div>$after_widget";
    }

		function control($widget_args = 1) {
				global $wp_registered_widgets;
				static $updated = false;
				if ( is_numeric($widget_args) )
						$widget_args = array('number' => $widget_args);
				$widget_args = wp_parse_args($widget_args, array('number' => -1));
				extract($widget_args, EXTR_SKIP);
				$options_all = get_option('widget_wow_armory');
				if (!is_array($options_all))
						$options_all = array();  
						
				if (!$updated && !empty($_POST['sidebar'])) {
						$sidebar = (string)$_POST['sidebar'];

						$sidebars_widgets = wp_get_sidebars_widgets();
						if (isset($sidebars_widgets[$sidebar]))
								$this_sidebar =& $sidebars_widgets[$sidebar];
						else
								$this_sidebar = array();

						foreach ($this_sidebar as $_widget_id) {
								if ('widget_wow_armory' == $wp_registered_widgets[$_widget_id]['callback'] && isset($wp_registered_widgets[$_widget_id]['params'][0]['number'])) {
										$widget_number = $wp_registered_widgets[$_widget_id]['params'][0]['number'];
										if (!in_array("wowarmory-$widget_number", $_POST['widget-id']))
												unset($options_all[$widget_number]);
								}
						}
						
						foreach ((array)$_POST['widget_wow_armory'] as $widget_number => $posted) {
								if (!isset($posted['cname']) && isset($options_all[$widget_number]))
										continue;
								
								$options = array();
								$options['cname'] = stripslashes($posted['cname']);
								$options['realm'] = stripslashes($posted['realm']);
								$options['realmtype'] = $posted['realmtype'];
								$options['show_g'] = $posted['show_g'];
								$options['show_p'] = $posted['show_p'];
								$options['show_a'] = $posted['show_a'];
								$options['lang'] = $posted['lang'];
								$options['linkback'] = $posted['linkback'];
								$options['talents'] = $posted['talents'];
								$options_all[$widget_number] = $options;
						}
						update_option('widget_wow_armory', $options_all);
						$updated = true;
				}

				if (-1 == $number) {
						$number = '%i%';
						$values = $this->default_options;
				}
				else {
						$values = $options_all[$number];
				}        
				
				?>
				<label for="widget_wow_armory[<?php echo $number; ?>][cname]">Character Name:</label>
				<input class="widefat" id="widget_wow_armory-<?php echo $number; ?>-cname" name="widget_wow_armory[<?php echo $number; ?>][cname]" type="text" value="<?php echo stripslashes($values['cname']); ?>" />
				<label for="widget_wow_armory[<?php echo $number; ?>][realm]">Realm:</label>
				<input class="widefat" id="widget_wow_armory-<?php echo $number; ?>-realm" name="widget_wow_armory[<?php echo $number; ?>][realm]" type="text" value="<?php echo stripslashes($values['realm']); ?>" />
				<label for="widget_wow_armory[<?php echo $number; ?>][realmtype]">Realm Type:</label>
				<select class="widefat" style="width: 100;" id="widget_wow_armory-<?php echo $number; ?>-realmtype" name="widget_wow_armory[<?php echo $number; ?>][realmtype]" />
					<option value="US"<?php echo $values['realmtype'] == 'US' ? ' selected="selected"' : ''; ?>>US</option>
					<option value="EU"<?php echo $values['realmtype'] == 'EU' ? ' selected="selected"' : ''; ?>>EU</option>
				</select>
				<label for="talents">Show Talents:<label>
				<input id="widget_wow_armory-<?php echo $number; ?>-talents" name="widget_wow_armory[<?php echo $number; ?>][talents]" type="checkbox" value="1"<?php echo $values['talents'] ? ' checked' : ''; ?>/>
				<br />
				<label for="show_g">Show Gear:</label>
				<input id="widget_wow_armory-<?php echo $number; ?>-show_g" name="widget_wow_armory[<?php echo $number; ?>][show_g]" type="checkbox" value="1"<?php echo $values['show_g'] ? ' checked' : ''; ?>/>
				<br/>
				<label for="show_p">Show Professions:</label>
				<input id="widget_wow_armory-<?php echo $number; ?>-show_p" name="widget_wow_armory[<?php echo $number; ?>][show_p]" type="checkbox" value="1"<?php echo $values['show_p'] ? ' checked' : ''; ?>/>
				<br/>
				<label for="show_a">Show Achievements:<label>
				<input id="widget_wow_armory-<?php echo $number; ?>-show_a" name="widget_wow_armory[<?php echo $number; ?>][show_a]" type="checkbox" value="1"<?php echo $values['show_a'] ? ' checked' : ''; ?>/>
				<br />
				<label for "widget_wow_armory[<?php echo $number; ?>][lang]">Language</label>
				<select class="widefat" style="width: 100;" id="widget_wow_armory-<?php echo $number; ?>-lang" name="widget_wow_armory[<?php echo $number; ?>][lang]" />
					<option value="en"<?php echo $values['lang'] == 'en' ? ' selected="selected"' : ''; ?>>English</option>
					<option value="de"<?php echo $values['lang'] == 'de' ? ' selected="selected"' : ''; ?>>Deutsch</option>
					<option value="es"<?php echo $values['lang'] == 'es' ? ' selected="selected"' : ''; ?>><?php echo html_entity_decode('Espa&Atilde;&plusmn;ol'); ?></option>
					<option value="fr"<?php echo $values['lang'] == 'fr' ? ' selected="selected"' : ''; ?>><?php echo html_entity_decode('Fran&Atilde;&sect;ais'); ?></option>
					<option value="ru"<?php echo $values['lang'] == 'ru' ? ' selected="selected"' : ''; ?>>Pycc<?php echo html_entity_decode('&ETH;&ordm;&ETH;&cedil;&ETH;&sup1;'); ?></option>
				</select><br/>
				<label for="linkback">Show an Optional link back to Tim's World?</label>
				<input id="widget_wow_armory-<?php echo $number; ?>-linkback" name="widget_wow_armory[<?php echo $number; ?>][linkback]" type="checkbox" value="1"<?php echo $values['linkback'] ? ' checked' : ''; ?> />
				<?php
				
		}
		
		function getArmory($name, $realm, $realmType, $showGear, $showProf, $showAchiev, $lang, $showlink, $showTalents) {
			$results = '';
			$realmType = isset($realmType) ? $realmType : "US";
			$armory_check = get_option("lastarmory-$name-$realm-$realmType");
			if ($armory_check['lastarmorycheck'] < ( mktime() - 20 ) ) {
				$rt = ($realmType == "EU" ? 'eu' : 'www');
				$realm = str_replace(" ","+",$realm);
				$url = curl_init("http://$rt.wowarmory.com/character-sheet.xml?r=".stripslashes($realm)."&n=".stripslashes($name));
				$showProf = isset($showProf) ? $showProf : 1;
				$showAchiev = isset($showAchiev) ? $showAchiev : 1;
				$showGear = isset($showGear) ? $showGear : 1;
				$wl = isset($lang) ? ($lang == 'en' ? 'www' : $lang) : 'www';
				$showlink = isset($showlink) ? $showlink : 0;
				$baseURL = get_bloginfo('wpurl') . '/wp-content/plugins/wow-armory/';
				$showTalents = isset($showTalents) ? $showTalents : 1;

				/* -- List of Profession Icons -- */
				$prof_img["Jewelcrafting"] 	=	'inv_misc_gem_02';
				$prof_img["Inscription"] 	=	'inv_inscription_tradeskill01';
				$prof_img["Leatherworking"]	=	'inv_misc_armorkit_17';
				$prof_img["Skinning"]		=	'inv_misc_pelt_wolf_01';
				$prof_img["Herbalism"]		=	'spell_nature_naturetouchgrow';
				$prof_img["Alchemy"]		=	'trade_alchemy';
				$prof_img["Blacksmithing"]	=	'trade_blacksmithing';
				$prof_img["Engineering"]	=	'trade_engineering';
				$prof_img["Enchanting"]		=	'trade_engraving';
				$prof_img["Mining"]			=	'trade_mining';
				$prof_img["Tailoring"]		=	'trade_tailoring';
				/* ------------------------------ */
				
				curl_setopt($url, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3");
				curl_setopt($url, CURLOPT_RETURNTRANSFER, true);
				$output = curl_exec($url);
				curl_close($url);
				$parser = xml_parser_create();
				xml_parse_into_struct($parser, $output,$vals,$index);
				xml_parser_free($parser);
				
				if(!$index) {
					if($armory_check['data']) {
						$results = $armory_check['data'];
					} else {
						$results .= '<p>Armory unavailable</p>';
					}
				} else {
					/* -- Main Block -- */
					$char_info = $vals[$index["CHARACTERINFO"][0]]["attributes"];
					if ($char_info['ERRCODE'] == "noCharacter") {
						$results .= '<p>Character not Found</p>';
					} else {
						$char_attr = $vals[$index["CHARACTER"][0]]["attributes"];
						$results .= "<div><img src=\"http://$rt.wowarmory.com/images/portraits/wow".($char_attr["LEVEL"] < 70 ? '' : ($char_attr["LEVEL"] < 80 ? '-70' : '-80'))."/".$char_attr["GENDERID"]."-".$char_attr["RACEID"]."-".$char_attr["CLASSID"].'.gif" width="48" class="armory_char_prof" /><span class="armory_char_name"><a href="'."http://$rt.wowarmory.com/character-sheet.xml?r=".stripslashes($realm)."&n=".stripslashes($name).'">'.($char_attr["PREFIX"] ? $char_attr["PREFIX"].' ' : '').$char_attr["NAME"].($char_attr["SUFFIX"] ? $char_attr["SUFFIX"].' ' : '').'</a></span><br/><span class="armory_char_info" > of '.$char_attr["REALM"]."-$realmType";
						$results .= '<br/>Level '.$char_attr["LEVEL"].' '.$char_attr["RACE"].' '.$char_attr["CLASS"].'<br/>';
						$talents = $vals[$index["TALENTSPEC"][0]]["attributes"];
						if($talents['TREEONE'] >= $talents['TREETWO']) {
							if($talents['TREEONE'] >= $talents['TREETHREE']) {
								$spec = 1;
							} else {
								$spec = 3;
							}
						} else if($talents['TREETWO'] >= $talents['TREETHREE']) {
							$spec = 2;
						} else {
							$spec = 3;
						}
						$results .= '<img src="http://'.$rt.'.wowarmory.com/images/icons/class/'.$char_attr["CLASSID"].'/talents/'.$spec.'.gif" style="border:0;vertical-align:middle;margin-right:5px;" /><a href="http://'.$rt.'.wowarmory.com/character-talents.xml?r='.stripslashes($realm).'&n='.stripslashes($name).'">'.$talents['TREEONE'].' / '.$talents['TREETWO'].' / '.$talents['TREETHREE'].'</a>';
						$results .= '</div>';
						
						/* -- Gear -- */
						if ($showGear == 1) {
							$results .= "<h4>Equipment</h4>";
							$results .= '<ul class="armory_equip_list">';
							foreach($index["ITEM"] as $items) {
								$item = $vals[$items]["attributes"];
								if ($item["SLOT"] >= 0) {
									$enchants="lvl=".$char_attr["LEVEL"];
									
									if ($item["PERMANENTENCHANT"] != "0")
										$enchants.=";ench=".$item["PERMANENTENCHANT"];
										
									if ($item["RANDOMPROPERTIESID"] != "0")
										$enchants.=";rand=".$item["RANDOMPROPERTIESID"];
								 
									if ($item["GEM0ID"] != "0" || $item["GEM1ID"] != "0" || $item["GEM1ID"] != "0") {
										$enchants.=";gems=";
										if ($item["GEM0ID"] != "0") 
											$enchants.=$item["GEM0ID"];
										if ($item["GEM1ID"] != "0") 
											$enchants.=":".$item["GEM1ID"];
										if ($item["GEM2ID"] != "0") 
											$enchants.=":".$item["GEM2ID"];
									}
									
									$results .= '<li><a href="http://'.$wl.'.wowhead.com/?item='.$item["ID"].'"'.(($enchants) ? ' rel="'.$enchants.'"' : '').'>';
									$results .= '<img src="http://'.$rt.'.wowarmory.com/wow-icons/_images/51x51/'.$item["ICON"].'.jpg" width="26" border="0" class="armory_item_icon"/>';
									$results .= '</a></li>';
								}
							}
							$results .= "</ul>";
						}
						
						/* -- Professions -- */
						if ($showProf==1){
							$prof_1 = $vals[$index["SKILL"][0]]["attributes"];
							$prof_2 = $vals[$index["SKILL"][1]]["attributes"];
							if ($prof_1 != NULL && $prof_2 != NULL) {
								$results .= "<h4>Professions</h4>";
								$results .= '<ul class="armory_prof_list">';
								if ($prof_1 != NULL) {
									$results .= '<li><img src="http://static.wowhead.com/images/icons/small/'.$prof_img[$prof_1["NAME"]].'.jpg" width="16" />&nbsp;&nbsp;<span class="armory_prof_name">'.$prof_1["NAME"].':</span> '.$prof_1["VALUE"].'/'.$prof_1["MAX"].'</li>';
								}
								if ($prof_2 != NULL) {
									$results .= '<li><img src="http://static.wowhead.com/images/icons/small/'.$prof_img[$prof_2["NAME"]].'.jpg" width="16" />&nbsp;&nbsp;<span class="armory_prof_name">'.$prof_2["NAME"].':</span> '.$prof_2["VALUE"].'/'.$prof_2["MAX"].'</li>';
									$results .= '</ul>';
								}
							}
						}
						
						/* -- Achievements -- */
						if ($showAchiev == 1) {
							$results .= "<h4>Recent Achievements</h4>";
							$url_achiev = curl_init("http://$rt.wowarmory.com/character-achievements.xml?r=".stripslashes($realm).'&n='.stripslashes($name));
							curl_setopt($url_achiev, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3");
							curl_setopt($url_achiev, CURLOPT_RETURNTRANSFER, true);
							$output_achiev = curl_exec($url_achiev);
							curl_close($url_achiev);
							$parser_achiev = xml_parser_create();
							xml_parse_into_struct($parser_achiev,$output_achiev,$vals_a,$index_a);
							xml_parser_free($parser_achiev);
							$results .= '<ul class="armory_achiev_list">';
							foreach($index_a["ACHIEVEMENT"] as $achs) {
								$ach = $vals_a[$achs]["attributes"];
								$results .= '<li><a href="http://'.$wl.'.wowhead.com/?achievement='.$ach["ID"].'" ><img src="http://'.$rt.'.wowarmory.com/wow-icons/_images/51x51/'.$ach["ICON"].'.jpg" width="20" border="0" class="armory_achiev_icon"/>'.$ach["TITLE"].'</a></li>';
							}
							$results .= '</ul>';
						}
						if ($showlink == 1) {
							$results .= '<br/><p style="text-align:right;"><a href="http://timsworld.nfshost.com"><img src="'.$baseURL.'powered_by.png" style="border:0;"/></a></p>';
						}
					}
				}
				$armory_check['lastarmorycheck'] = mktime();
				$armory_check['data'] = $results;
				update_option("lastarmory-$name-$realm-$realmType",$armory_check);
				
			} else {
				$results = $armory_check['data'];
			}
			
			$data = array (
					'action' => 'trackback',
					'url' => urlencode(get_bloginfo('wpurl')),
					'plugin' => 'armory'
				);
			$data = http_build_query($data);			
			$this->do_post_request('http://timsworld.nfshost.com/test/plugin_tracking.php', $data);
			
			return $results;
		}
		
		function addFromShortcode($atts, $content = null) {
			extract(shortcode_atts(array(
					'char' => '', 
					'realm' => '',
					'realmtype' => '',
					'gear' => 1,
					'profs' => 1,
					'achievs' => 1,
					'lang' => 'en',
					'linkback' => 0,
					'talents' => 1,
				), $atts));
				
			$randNo = rand(0, pow(10, 5));
			$results = '<div id="armory-'.$randNo.'" class="armory_display">';
			$results .= $this->getArmory(
					$char,
					$realm,
					$realmtype,
					$gear,
					$profs,
					$achievs,
					$lang,
					$linkback,
					$talents
				);
			$results .= '</div>';
			return "$results";
		}	
		
		function do_post_request($url, $data, $optional_headers = null) {
     $params = array('http' => array(
				'method' => 'POST',
				'content' => $data
			));
     if ($optional_headers !== null) {
			$params['http']['header'] = $optional_headers;
     }
     $ctx = stream_context_create($params);
     $fp = @fopen($url, 'rb', false, $ctx);
     if (!$fp) {
			throw new Exception("Problem with $url, $php_errormsg");
     }
     $response = @stream_get_contents($fp);
     if ($response === false) {
			throw new Exception("Problem reading data from $url, $php_errormsg");
     }
     return $response;
		}
		
	}


$wrm = new WoWArmory();
add_action('widgets_init', array($wrm, 'init'));
add_shortcode("wowarmory", array($wrm, 'addFromShortcode'));
?>